﻿using System;
using System.Web.Mvc;
using System.Linq;
using OneDollarStore.Models;

namespace OneDollarStore.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        StoreModelEntities storeDB = new StoreModelEntities();
        
        // RedirectToRouteResult
        public RedirectToRouteResult Index()
        {
            return RedirectToAction("Index", "Product");
        }

        // ViewResult
        public ViewResult About()
        {
            // URL: /Home/About
            return View();
        }

        public ViewResult ContactUs()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ContactUs(ContactModel contactModel)
        {
            if (ModelState.IsValid)
            {
                return RedirectToAction("ContactUsSuccessOrFail", contactModel);
            }
            else
            {
                return View();
            }
        }

        public ViewResult ContactUsSuccessOrFail(ContactModel contactModel)
        {
            try
            {
                Feedback feedback = new Feedback()
                {
                    Name = contactModel.Name,
                    Email = contactModel.Email,
                    Title = contactModel.Title,
                    Content = contactModel.Content
                };
                storeDB.AddToFeedbacks(feedback);
                storeDB.SaveChanges();
                ViewData["ContactUs"] = "Success";
                return View();
            }
            catch (Exception ex)
            {
                ViewData["ContactUs"] = "Fail";
                Response.Write(ex.Message);
                return View();
            }
        }

        public ViewResult HomePage()
        {
            return View();
        }

        public ViewResult News()
        {
            var newsModel = (from news in storeDB.News
                             orderby news.DateCreated descending
                             select news);
            return View(newsModel);
        }

        public ViewResult PriceList()
        {
            var products = (from product in storeDB.SerialProducts.Include("Category").Include("Laptop")
                            .Include("Desktop").Include("Mainboard").Include("CPU").Include("RAM")
                            .Include("HDD").Include("VGA")
                            orderby product.Category.Name, product.Name
                            select product);
            return View(products);
        }
    }
}